#include "TLV.hpp"


TLV::TLV() : type(0), length(0) {
    memset(data, 0, sizeof(data));
}

TLV::TLV(int t, int l, const string& d) 
: type(t), length(l) 
{
    if (d.length() > 1023) {
        throw invalid_argument("Data too long for TLV");//抛出错误
    }
    memcpy(data, d.c_str(), d.length());
    data[d.length()] = '\0';
}

TLV::~TLV() {};

void TLV::setType(int t) {
    type = t;
}

void TLV::setLength(int l) {
    length = l;
}

void TLV::setData(const string& d) {
    if (d.length() > 1023) {
        throw invalid_argument("Data too long for TLV");//抛出错误
    }
    memcpy(data, d.c_str(), d.length());
    data[d.length()] = '\0';
}

string TLV::TLVtoString() const 
{
    string result;
    result.resize(sizeof(int) * 2 + length); // 调整字符串长度为:type + length + data
    memcpy(&result[0], &type, sizeof(int));
    memcpy(&result[sizeof(int)], &length, sizeof(int));
    memcpy(&result[sizeof(int) * 2], data, length);
    return result;
}

TLV TLV::StringtoTLV(const string& buf) {
    TLV tlv;
    if (buf.size() < sizeof(int) * 2) {
        throw std::invalid_argument("Buffer too short to be a valid TLV");//缓冲区太小了，报错
    }
    memcpy(&tlv.type, &buf[0], sizeof(int));
    memcpy(&tlv.length, &buf[sizeof(int)], sizeof(int));
    
    if (tlv.length < 0 || tlv.length > 1023 || buf.size() < sizeof(int) * 2 + tlv.length) {
        throw std::invalid_argument("Invalid TLV length field");//长度字段无效
    }
    
    memcpy(tlv.data, &buf[sizeof(int) * 2], tlv.length);
    tlv.data[tlv.length] = '\0';
    return tlv;
}
